import React from 'react';
import PropTypes from 'prop-types';

import BaseComponent from './baseComponent.js';
import { debounced } from '../../utils/func';

class Button extends BaseComponent {
  static propTypes = {
    clickFunc: PropTypes.func.isRequired,
    disabled: PropTypes.bool,
    loading: PropTypes.bool,
    title: PropTypes.string.isRequired,
    interval: PropTypes.number,
  }
  static defaultProps = {
    disabled: false,
    loading: false,
    interval: 300,
  }

  intervalClick = debounced(this.props.clickFunc, this.props.interval);

  clickBtn = () => {
    const {
      clickFunc, disabled, loading, interval,
    } = this.props;
    if (!disabled && !loading) {
      if (interval > 0) {
        this.intervalClick();
      } else {
        clickFunc();
      }
    }
  }

  render() {
    const {
      className,
      disabled,
      title,
      loading,
    } = this.props;
    let cls;
    let loadingView;
    if (disabled) {
      cls = `base-btn ${className} btn-disabled`;
    } else if (loading) {
      cls = `base-btn ${className}`;
      loadingView = <div className="btn-loading"><i className="iconfont icon-loading spinner" /></div>;
    } else {
      cls = `base-btn ${className}`;
    }
    return (
      <div onClick={this.clickBtn} className={cls}>
        <div>{title}</div>
        {loadingView}
      </div>
    );
  }
}

export default Button;

